package com.grid.action;
import java.sql.*;
import java.util.*;


import com.grid.model.Application;
import com.grid.model.Applications;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import java.io.StringReader;
import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class GetApplicationDetails extends ActionSupport {

	private ArrayList<String> ApplicationNames = new ArrayList<String>();

	public ArrayList<String> getApplicationNames() {
		return ApplicationNames;
	}

	public void setApplicationNames(ArrayList<String> applicationNames) {
		ApplicationNames = applicationNames;
	}
	
	private ArrayList<Application> ApplicationList = new ArrayList<Application>();

	
	
	public ArrayList<Application> getApplicationList() {
		return ApplicationList;
	}

	public void setApplicationList(ArrayList<Application> applicationList) {
		ApplicationList = applicationList;
	}

	public String execute(){
	
		System.out.println("in execute of web service client");
		ClientConfig config = new DefaultClientConfig();
	    Client client = Client.create(config);
	    WebResource service = client.resource(getBaseURI());

	    
	    String xml = service.path("rest").path("todo").accept(MediaType.APPLICATION_XML).get(String.class);
	    System.out.println("xml is " + xml);
	    
	    Applications res = new Applications();
	    
	    try
	    {
		    JAXBContext ctx = JAXBContext.newInstance(Applications.class);
	        Unmarshaller um = ctx.createUnmarshaller();
	        res = (Applications)um.unmarshal(new StringReader(xml));
	    }
	    catch(Exception ex){
	    	System.out.println("jaxb exception occured");
	    }
        
	    ApplicationList = res.getApplicationList();
	    
	    for(Application temp : ApplicationList){
	    	
	    	System.out.println("name is "+temp.getApplicationName());
	    	ApplicationNames.add(temp.getApplicationName());
	    }
	    
	    return SUCCESS;
	}
	
	private static URI getBaseURI() {
	    return UriBuilder.fromUri("http://localhost:8080/HealthGridWebService").build();
	  }
	
}
